import axios from 'axios'
import {useUserStore} from "@/sotre";
import router from "@/router";
import api from "@/api/index";

axios.defaults.baseURL = "/piccAPI"
const userStore = useUserStore()


//设置请求拦截器
axios.interceptors.request.use((config) => {
    // 携带上token
    let token = userStore.token
    // @ts-ignore
    token && (config.headers.Authorization = token)
    return config
}, error => {
    return Promise.reject(error)
})

//响应拦截器
axios.interceptors.response.use(
    // @ts-ignore
    (response) => {
        //refreshToken过期 返回主页
        if (response && response.data.code === 420) {
            window.$message.warning("请登录")
            router.push({
                path: '/login'
            })
            window.$loadingBar.finish()
            return
        }
        //token过期 refreshToken更新token
        if (response && response.data.code === 410) {
            api.auth.refreshToken({
                'refreshToken': userStore.refreshToken
            }).then((res: any) => {
                if (res && res.data.code === 0) {
                    window.$message.warning("请稍后重试")
                    userStore.setToken(res.data.data.token)
                    userStore.setRefreshToken(res.data.data.refreshToken)
                    window.$loadingBar.finish()
                }
            })
            return
        }
        if (response && response.data.code !== 0) {
            window.$message.error(response.data.msg)
            window.$loadingBar.finish()
            // return Promise.reject(new Error(response.data.msg))
            return
        }
        return response;
    }, (error => {
        // 请求错误时做些事
        let res = "";
        if (error.request) {
            res = error.request;
        } else if (error.response) {
            res = error.response;
        }
        if (res) {
            //@ts-ignore
            const data = JSON.parse(res.response)
            window.$message.error(data.msg)
        } else {
            window.$message.error(`链接服务器失败`)
            error.message = "连接服务器失败!";
        }
        return Promise.reject(error);
    })
)

export default axios
